#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

//  客户端
//  输入  ./UdpClient ip  port
int main(int argc, char *argv[])
{
    //  先通过输入拿到 ip 和 port
    if (argc != 3)
    {
        cerr << "Usage:" << argv[0] << " Client_ip  Client_port" << endl;
        return 1;
    }
    uint16_t _port = stoi(argv[2]);
    string _ip = argv[1];

    //  选定网络协议
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        return 2;
    }
    cout << "Client socket success" << endl;

    //  初始化发送信息的结构体信息
    struct sockaddr_in Client;
    bzero(&Client, sizeof(Client));

    Client.sin_family = AF_INET;
    Client.sin_port = htons(_port);
    Client.sin_addr.s_addr = inet_addr(_ip.c_str());

    while (true)
    {
        //  输入信息发送结构体
        string message;
        cout << "Please Enter:";
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)&Client, sizeof(Client));

        //  接收返回信息
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len;
        int n = recvfrom(sockfd, &buffer, sizeof(buffer), 0, (sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "recvfrom success:" << buffer << endl;
        }
    }
    return 0;
}